package com.iflytek.uoamp.agent.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.log4j.Logger;

public class ReadFile {

	/**
	 * 按编码读取文件
	 * 
	 * @param file
	 * @param encoding
	 * @return
	 */
	public static String readAll(String file, String encoding) {
		try {
			byte[] content = readAll4Byte(file);
			return new String(content, encoding);// "EncodingGuess.getEncoding(fileBuff));
		} catch (Exception e) {
			Logger.getRootLogger().error(e.getMessage(), e);
			return "";
		}
	}

	/**
	 * 按字节读取文件
	 * 
	 * @param file
	 * @return
	 */
	public static byte[] readAll4Byte(String file) {

		File f = new File(file);
		byte[] fileBuff = new byte[(int) f.length()];
		FileInputStream in = null;
		try {
			in = new FileInputStream(f);
			in.read(fileBuff);
			return fileBuff;
		} catch (Exception e) {
			Logger.getRootLogger().error("can't get file :" + file, e);
			return null;
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				Logger.getRootLogger().error("can't close FileInputStream", e);
			}
		}
	}

	/***
	 * 按字节读取文件，可以选择跳过特定的字节
	 * 
	 * @param file
	 *            需要读取的文件
	 * @param skip
	 *            跳过的字节数
	 * @param readSize
	 *            读取的字节数
	 * @return
	 */
	public static byte[] read4Byte(String file, long skip, long readSize) {

		File f = new File(file);
		if ((f.length() - skip) < readSize) {
			readSize = f.length() - skip;
		}
		byte[] fileBuff = new byte[(int) readSize];
		FileInputStream in = null;
		try {
			in = new FileInputStream(f);
			in.skip(skip);
			in.read(fileBuff);
			return fileBuff;// "EncodingGuess.getEncoding(fileBuff));
		} catch (Exception e) {
			Logger.getRootLogger().error("can't get file :" + file, e);
			return null;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				Logger.getRootLogger().error("can't close FileInputStream", e);
			}
		}
	}

}
